/* -*- Mode: c; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil; -*- */
/*
  RefObject (http://code.google.com/p/refobject/)
  Copyright (C) 2010-2011 MIURA Shirow (sharow)
*/

#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <setjmp.h>
#include <cmockery.h>

#include <RefObject/RefObjectAll.h>
#include "test_common.h"


static void
test_RefDict_Create0(void **state)
{
    RefObject *dict;
    dict = RefDict_Create();
    assert_true(dict != NULL);
    RefObject_DecRef(dict);
}

static void
test_RefDict_SetGetItem0(void **state)
{
    RefObject *dict;
    RefObject *value[2];
    RefObject *rvalue;
    int result;
    dict = RefDict_Create();

    value[0] = RefInt_Create(0);
    value[1] = RefInt_Create(1);

    result = RefDict_SetItemCString(dict, "zero", 4, value[0]);
    assert_true(result == 0);

    rvalue = RefDict_GetItemCString(dict, "zer", 3);
    assert_true(rvalue == NULL);

    rvalue = RefDict_GetItemCString(dict, "zere", 4);
    assert_true(rvalue == NULL);

    rvalue = RefDict_GetItemCString(dict, "zer\0", 4);
    assert_true(rvalue == NULL);

    rvalue = RefDict_GetItemCString(dict, "zero", 4);
    assert_true(rvalue != NULL);
    assert_true(RefInt_IsValid(rvalue));
    assert_true(RefInt_AsInt(rvalue) == 0);

    RefObject_DecRef(value[1]);
    RefObject_DecRef(value[0]);
    RefObject_DecRef(dict);
}

static void
test_RefDict_SetGetItem1(void **state)
{
    RefObject *dict;
    RefObject *value;
    RefObject *rvalue;
    int result;
    int i;
    char key_strings[100][5];

    dict = RefDict_Create();
    value = RefInt_Create(0);

    for (i = 0; i < 100; i++) {
        int j;
        for (j = 0; j < sizeof(key_strings[0]) / sizeof(key_strings[0][0]) - 1; j++) {
            key_strings[i][j] = (rand() % ('z' - 'a')) + 'a';
        }
        key_strings[i][4] = '\0';
        /*printf("%d key=%s\n", i, key_strings[i]);*/
        result = RefDict_SetItemCString(dict, key_strings[i], 4, value);
        assert_true(result == 0);
        assert_true(RefDict_GetSize(dict) == i+1);
    }

    /* check */
    for (i = 0; i < 100; i++) {
        rvalue = RefDict_GetItemCString(dict, key_strings[i], 4);
        assert_true(rvalue != NULL);
        assert_true(RefInt_IsValid(rvalue));
        assert_true(RefInt_AsInt(rvalue) == 0);
    }

    RefObject_DecRef(value);
    RefObject_DecRef(dict);
}

int
test_RefDict(void)
{
    const UnitTest tests[] = {
        unit_test(null_test_success),
        unit_test_setup_teardown(test_RefDict_Create0, setup, teardown),
        unit_test_setup_teardown(test_RefDict_SetGetItem0, setup, teardown),
        unit_test_setup_teardown(test_RefDict_SetGetItem1, setup, teardown)
    };
    return run_tests(tests);
}

